package com.tsl.prevention.modules.user.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsl.prevention.modules.user.entity.Info;
import com.tsl.prevention.modules.user.service.IInfoService;
import com.tsl.prevention.modules.wechat.serviceImpl.WeixinServiceImpl;
import com.tsl.prevention.util.PageFilter;
import com.tsl.prevention.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author Lionel
 * @since 2021-03-17
 */
@RestController
@RequestMapping("/user/info")
@Api("社区业主管理")
public class InfoController {
    @Autowired
    private IInfoService infoService;
    @Autowired
    private WeixinServiceImpl weixinService;

    @ApiOperation("新增业主")
    @PostMapping("/insertUser")
    public Result insertUser(@RequestBody Info info) {
        infoService.save(info);
        return Result.create(200, "创建成功");
    }

    @GetMapping("/selectUser")
    @ApiOperation("根据id查询用户")
    public Result selectUser(String openId) {
        Info info = infoService.getOne(new QueryWrapper<Info>().eq("open_id", openId));
        if (info != null) {
            return Result.create(info);
        } else {
            return Result.create(500, "用户不存在");
        }
    }

    @GetMapping("/getList")
    @ApiOperation("获取指定用户列表")
    public Result getList(Page page, String type) {
        //查询是否是所有人口
        QueryWrapper<Info> queryWrapper = new QueryWrapper<>();
        if (type != null) {
            queryWrapper.eq("type", type);
        }
        IPage<Info> list = infoService.page(page, queryWrapper);
        return Result.create(list);
    }

    @PutMapping("/updateUser")
    @ApiOperation("跟新用户")
    public Result updateUser(@RequestBody Info info) {
        boolean b = infoService.updateById(info);
        return Result.create();
    }

    /**
     * 向指定URL发送GET方法的请求
     * @param url 发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "/" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    @GetMapping("/getDay")
    public Result getDay() {
        String s = sendGet("https://gwpre.sina.cn/interface/news/wap/historydata.d.json?province=guangxi&callback=_aProvinceFunction&_=1585398242301", null);
        String s1 = s.replaceAll("_aProvinceFunction\\(", " ");
        String s2 = s1.replaceAll("\\);", " ");
        Map parse = (Map) JSON.parse(s2);
        return Result.create(parse);
    }

    @GetMapping("/getOpenId")
    @ApiOperation("获取openId")
    public Result getOpenId(String code) {
        JSONObject userWXLoginInfo = weixinService.getUserWXLoginInfo(code);
        return Result.create(userWXLoginInfo);
    }

    //查看本地和外地人员比例
    @GetMapping("/getProportion")
    @ApiOperation("查看本地和外地人员比例")
    public Result proportion() {
       HashMap<String,String> map =  infoService.getProportion();
       return Result.create(map);
    }

}

